package com.huluobo.a2109mvpimdemo;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;

import com.huluobo.a2109mvpimdemo.chat.ChatActivity;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseIM;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LC on 2023/11/10.
 */
public class IMApp extends Application {

    //3-20位字符,首字符必须为英文
    public static final String REGEX_USERNAME = "^[a-zA-Z]\\w{2,19}$";
    //3-20位数字
    public static final String REGEX_PASSWORD = "^[0-9]{3,20}$";

    public static final String SP_USERNAME = "username";
    public static final String SP_PASSWORD = "password";

    //声音池,类似线程池,setMaxStreams(10)设置最大线程数
    private SoundPool soundPool = new SoundPool.Builder().setMaxStreams(10).build();

    //处于前台的消息提醒
    private int duan;
    //处于后台的消息提醒
    private int yulu;

    private EMMessageListener emMessageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            if (isForeground()) {
                Log.i("TagA", "应用处于前台位置,不弹通知");
                //声音id,左声道,右声道,优先级,循环次数,播放速度
                soundPool.play(duan, 1f, 1f, 0, 0, 1f);
            } else {
                soundPool.play(yulu, 1f, 1f, 0, 0, 1f);
                showNotification(messages);
            }
        }
    };

    private void showNotification(List<EMMessage> messages) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        for (int i = 0; i < messages.size(); i++) {
            String contentText = "文本";
            if (messages.get(i).getType() == EMMessage.Type.TXT) {
                //文本消息
                contentText = ((EMTextMessageBody) messages.get(i).getBody()).getMessage();
            } else if (messages.get(i).getType() == EMMessage.Type.IMAGE) {
                contentText = "[图片]";
            } else if (messages.get(i).getType() == EMMessage.Type.FILE) {
                contentText = "[文件]";
            }

            Intent intent = new Intent(this, ChatActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("conversationId", messages.get(i).conversationId());

            //得判断这条消息到底是群聊消息还是单聊消息
            if (messages.get(i).getChatType() == EMMessage.ChatType.Chat) {
                bundle.putInt("chatType", 1);
            } else {
                bundle.putInt("chatType", 2);
            }
            intent.putExtras(bundle);

            TaskStackBuilder taskStackBuilder =
                    TaskStackBuilder.create(this).addParentStack(ChatActivity.class).addNextIntent(intent);
            PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);


//            PendingIntent pendingIntent =
//                    PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            Notification notification = new Notification.Builder(this)
                    .setContentTitle("收到新消息")//通知的标题
                    .setContentText(contentText)//通知的内容
                    .setSmallIcon(R.mipmap.wechat)//小图标,***注意*** 小图标必须要有,没有通知弹出不来
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.wechat))//设置通知大图标
                    .setAutoCancel(true)//设置是否自动取消
                    .setContentIntent(pendingIntent)
                    .build();

            notificationManager.notify(1, notification);
        }
    }

    //判断当前引用是否处于前台位置
    private boolean isForeground() {
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

        //循环当前手机中正在运行的app进程信息
        //ActivityManager.RunningAppProcessInfo 正在运行的进程信息
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : activityManager.getRunningAppProcesses()) {
            //对比当前运行信息中优先级是否等于前台的优先级
            return runningAppProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
        }
        return false;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EMOptions options = new EMOptions();
        options.setAppKey("moroks#2109mvpimdemo");
//        EMClient.getInstance().init(this, options);

        //EaseIM 初始化
        if (EaseIM.getInstance().init(this, options)) {
            //在做打包混淆时，关闭 debug 模式，避免消耗不必要的资源
            EMClient.getInstance().setDebugMode(true);
            //EaseIM 初始化成功之后再调用注册消息监听的代码 ...
        }

        ZXingLibrary.initDisplayOpinion(this);

        EMClient.getInstance().chatManager().addMessageListener(emMessageListener);

        duan = soundPool.load(this, R.raw.duan, 0);
        yulu = soundPool.load(this, R.raw.yulu, 0);
    }
}
